import store from '@/store'

function checkPermission(el, binding) {
  const { value } = binding

  if (value && typeof value === 'string' && value.length > 0) {
    const permission = store.state.permission.directives // 服务器传回的指令权限列表(url + role)
    const directive = value // 校验的内容，v-permission 传入的内容（v-permission="'/user/user/update'"）
    const roles = store.getters && store.getters.roles // 用户具有的角色

    let hasPermission = true
    permission.forEach(onePermission => {
      if (onePermission.url === directive) {
        hasPermission = false
        roles.forEach(userRole => {
          // 如果用户具有角色，就有权限
          if (onePermission.role.includes('|' + userRole + '|')) {
            hasPermission = true
            return
          }
        })
        return
      }
    })

    // 没有权限，删除元素
    if (!hasPermission) {
      el.parentNode && el.parentNode.removeChild(el)
    }
  }
}

export default {
  inserted(el, binding) {
    checkPermission(el, binding)
  },
  update(el, binding) {
    checkPermission(el, binding)
  }
}
